<?php

class Member extends MY_Controller {

    protected $_lang = 'vn';

    function __construct() {
        parent::__construct();
        $this->session->set_userdata(array('Url' => uri_string()));
        $this->_lang = $this->lang->lang();
        $this->load->model('member_model', 'member');
//		$this->load->model('public_model','public');
//        $this->lang->load('error');
        $this->lang->load('member');
        $this->load->library('securimage');
        $this->load->helper('phpmailer');
        $this->lang->load('mailsubject');
        $this->config->load('config_globalvar', TRUE);
    }

    function index() {
        $ses_login = get_ses_login();
        if (!empty($ses_login)) {
            echo '<ul>
				 <li><a href="javascript:fn_logout()" style="color:#F00;">Logout</a></li>
				 <li><a href="' . base_url() . 'congdong/status" target="congdong"><img src="' . base_url() . 'templates/images/msg_envelope.png" alt="Tin nhắn"></a>&nbsp;<img src="' . base_url() . 'templates/images/msg_bell.png" alt="Thư"></li>
				 <li><div id="userlogin"><a href="' . base_url() . 'congdong"  target="congdong">Welcome ' . $ses_login["lb_user_login"] . '</a></div></li>
			  </ul>';
        } else {
            echo '<ul>
				  <li><a onClick="hidelogin();" href="javascript:page.load(\'member/register\',\'mainpage\');">Đăng ký</a></li>
				 <li><a class="sign_in" href="javascript:void(0);" onClick="showlogin()">Đăng nhập</a></li>
			  </ul>';
        }
    }

    function register() {
        $data = array();
        $data['timezones'] = $this->config->item('fm_time_zone', 'config_globalvar');
        $this->_templates['page'] = 'register_view';
        // page title
        $data['title_page'] = lang('anw.register');

        $this->site_lib->load($this->_templates['page'], $data);
    }

    function policies_terms() {
        $this->load->model('staticpage_model', 'staticpage');
        $this->staticpage->initialise($this->_lang);

        $data['policies'] = $this->staticpage->getStaticByCode('policies_terms');

        $this->_templates['page'] = 'member/policies_tearm_view';
        $data['title_page'] = lang('anw.register');
        $this->site_lib->load($this->_templates['page'], $data);
    }

    function do_register() {
        if (!empty($_POST)) {
            $this->form_validation->set_rules('lb_user_login', 'Login Name', 'trim|required');
            $this->form_validation->set_rules('lb_full_name', 'Full Name', 'trim|required');
            $this->form_validation->set_rules('lb_password', 'Password', 'trim|required');
            $this->form_validation->set_rules('lb_email', 'Email', 'trim|required');
            $this->form_validation->set_rules('code', 'Code', 'trim|required');
            $data['error'] = 1;
            if ($this->form_validation->run() == FALSE) {
                $this->pre_message = validation_errors();
                $data['mess'] = $this->pre_message;

                $data['success'] = false;
                echo json_encode($data);
                exit;
            } else {
                $code = $this->input->post('code');
                if (!$this->securimage->check($code)) {
                    $data['mess'] = lang('reg.captcha_incorrect');
                    $data['success'] = false;
                    echo json_encode($data);
                } else {
                    $rs = $this->member->check_email($_POST['lb_email']);
                    if (empty($rs)) {
                        $data = $this->build_data($_POST, 1);
                        $rs = $this->member->save_member(0, $data);
                        if ($rs > 0) {
                            $_SESSION['username'] = $_POST['lb_user_login'];
                            $_SESSION['member_id'] = $rs;
                            $data['success'] = true;
                            $data['mess'] = lang('reg.successful');

                            /* Begin send email */
                            $email = $this->input->post('lb_email');

                            $data_mail['user_name'] = $this->input->post('lb_full_name');
                            $data_mail['contact_mail'] = $this->config->item('contact_email');
                            $data_mail['admin_email'] = $this->config->item('admin_email');
                            $data_mail['site_name'] = $this->config->item('site_name');
                            $data_mail['site_url'] = $this->config->item('base_url');
                            $data_mail['confirm_url'] = site_url('member/activeuser/' . $rs . '/' . md5($email));

                            $subject = $this->lang->line('mailsubject_active_user');
                            $message = $this->load->view('emails/' . $this->_lang . '/user_active_email', $data_mail, true);

                            $rs_email = send_email($this->config->item('admin_email'), $email, $this->config->item('contact_email'), $subject, $message);
                            if ($rs_email) {
                                $this->member->save_member($rs, array('bl_send_email_active' => 1));
                                //$data['lb_email']=$rs['lb_email'];
                                //$data['show_success']=true;
                            } else {
                                //$data['mess']='';
                            }
                            //End send email

                            echo json_encode($data);
                        } else {
                            $data['success'] = false;
                            $data['mess'] = lang('reg.error_save_data');
                            echo json_encode($data);
                        }
                    } else {
                        $data['success'] = false;
                        $data['mess'] = lang('reg.email_existed');
                        echo json_encode($data);
                    }
                }
            }
        }
    }

    function forget_pass() {
        $this->load->helper('phpmailer');
        $this->load->model('email_model', 'email');
        $this->email->initialise($this->_lang);
        $data['show_success'] = false;
        $data['err'] = 0;
        $data['lb_email'] = '';
        if (!empty($_POST) && ($action == 'send')) {

            $email = $this->input->post('lb_email');
            $comfim_email = $this->input->post('comfim_email');

            $rs = $this->member->check_email($email);
            if (!empty($rs)) {
                $newpass = substr(uniqid(md5(time())), 0, 6);
                $data_pass = array('lb_password' => md5($newpass));

                if ($this->member->save_member($rs['member_id'], $data_pass)) {
                    $message = $this->load->view('emails/vn/user_forgot_pass_email', $data_mail, true);
                    if ($rs_template) {
                        $user_name = $rs['lb_full_name'];
                        $lb_password = $newpass;
                        $subject = $rs_template->subject;
                        $template_text = addslashes($rs_template->content);
                        eval("\$message=\"$template_text\";");

                        $rs_email = send_email($this->config->item('admin_email'), $email, $this->config->item('contact_email'), $subject, $message);
                        if ($rs_email) {
                            $data['lb_email'] = $rs['lb_email'];
                            $data['show_success'] = true;
                        } else {
                            
                        }
                    }
                } else {
                    
                }
            } else {
                $data['err_mess'] = lang('reg.err_user_not_exist');
                $data['err'] = 1;
            }
        }
        $type = $this->input->post('type');

        if ($type == 'ajax') {
            echo $this->load->view('register/forgot_pass', $data, true);
        } else {
            $this->_templates['page'] = 'register/forgot_pass';
            $this->site_lib->load($this->_templates['page'], $data);
        }
    }

    function activeuser($member_id, $hash) {
        $data = array();
        $member = $this->member->get_member($member_id);
        if ($member) {
            if ($hash != '' && ($hash == md5($member['lb_email'])) && $member['bl_active'] == 1) {
                $data['str_mess'] = lang('reg.account_activated');
            } else if ($hash != '' && ($hash == md5($member['lb_email']))) {
                $this->member->save_member($member_id, array('bl_active' => 1));
                $data['str_mess'] = lang('reg.activated_successful');
            } else {
                $data['str_mess'] = lang('reg.activate_mistake') . '&nbsp;:&nbsp;<a href="mailto:' . $this->config->item('contact_email') . '">' . $this->config->item('contact_email') . '</>';
            }
        } else {
            $data['str_mess'] = lang('reg.member_not_exist');
        }
        $this->_templates['page'] = 'login/active_user';
        $this->site_lib->load($this->_templates['page'], $data);
    }

    //binh.ngo buid data to insert or update
    function build_data($data, $flag = 1) {
        //flag=10?insert:update
        $dataUpdate["lb_full_name"] = trim($data["lb_full_name"]);
        if (!empty($data["lb_image"])) {
            $dataUpdate["lb_image"] = trim($data["lb_image"]);
        }
        $dataUpdate["lb_user_login"] = trim($data["lb_user_login"]);
        $dataUpdate["lb_email"] = trim($data["lb_email"]);
        $dataUpdate['nb_gender'] = $data['nb_gender'];
        if ($data['nb_gender'] == 1)
            $dataUpdate['lb_image'] = "avatar_male.jpg";
        else
            $dataUpdate['lb_image'] = "avatar_female.jpg";
        $dataUpdate['lb_birthday'] = $data['lb_day'] . '/' . $data['lb_month'] . '/' . $data['lb_year'];
        $dataUpdate["timezoneoffset"] = trim($data["timezoneoffset"]);
        if (!empty($data["bl_mail_orther"]))
            $dataUpdate["bl_mail_orther"] = trim($data["bl_mail_orther"]);
        if (!empty($data["bl_mail_admin"]))
            $dataUpdate["bl_mail_admin"] = trim($data["bl_mail_admin"]);

        if ($flag == 1) {
            $dataUpdate["dt_create"] = date('Y-m-d H:i:s');
            $dataUpdate["lb_password"] = md5(trim($data["lb_password"]));
        }
        if (!empty($data["bl_active"]))
            $dataUpdate["bl_active"] = (int) trim($data["bl_active"]);

        return $dataUpdate;
    }

    function save() {
        $data = $this->build_data($_POST, $flag = 1);
        if ($this->album->save_member($data)) {
            return true;
        } else {
            return false;
        }
    }

    function login_member() {
        $rs = $this->checkMemberLogin($_POST['lb_user_login'], $_POST['lb_password']);
        if ($rs) {
            return true;
        } else {
            return false;
        }
    }

    //check login
    //binh.ngo
    function is_login() {
        $success = true;
        $ses_login = isset($_SESSION['ses_login']) ? $_SESSION['ses_login'] : '';
        if (!empty($ses_login['member_id'])) {
            $data['member_id'] = $_SESSION['ses_login']['member_id'];
            $data['lb_user_login'] = $_SESSION['ses_login']['lb_user_login'];
            $code = $_SESSION['ses_login']['member_id'] . $_SESSION['ses_login']['lb_user_login'];
            $data['code'] = md5($code);
        } else {
            $success = false;
            $data['member_id'] = "";
            $data['lb_user_login'] = "";
            $data['code'] = "";
        }
        $data['success'] = $success;
        echo json_encode($data);
    }

    ///tritigi: 10-05-2012: login form =>user can login truoc khi goi comment
    function comment_login() {
        $data = array();
        $this->load->view("member/signin", $data);
        //$this->load->view("member/comment_login",$data) ;
    }

    /*
     * @author: Vo Van Hieu
     */

    function login() {
        $email = $this->input->post('email');
        $pass = $this->input->post('pass');
        $remember = $this->input->post('remember');

        $rs = $this->member->checkMemberLogin($email, $pass);
        if ($rs) {
            $data['member_id'] = $rs['member_id'];
            $data['lb_user_login'] = $rs['lb_user_login'];
            $data['message'] = '';
            $data['lb_email'] = $rs['lb_email'];
            $_SESSION['ses_login'] = $rs;

            if ($remember == 1) {
                $remember_key = md5(time());
                $rs_insert_remember = $this->member->insert_rememberme(array('member_id' => $rs['member_id'], 'hashkey' => $remember_key));
                $time_cookie = time() + (3600 * 24 * 365);
                setcookie('ses_login_rm_id', addslashes($remember_key), $time_cookie, '/');
                $_COOKIE['ses_login_rm_id'] = addslashes($remember_key);
            }
            $data['success'] = true;
            $data['code'] = '';
        } else {
            $data['success'] = false;
            $data['code'] = 'LOGIN_FAIL';
        }
        echo json_encode($data);
    }

    //tritigi: 10-05-2012: xu ly load form quen password;
    function lostpass() {
        $data = array();
        $this->_templates['page'] = 'member/lostpass';
        $this->load->view($this->_templates['page'], $data);
    }

    //tritigi: 10-05-2012: thong tin thanh vien = profile
    function profile() {
        $data = array();
        $this->_templates['page'] = 'member/profile';
        $this->load->view($this->_templates['page'], $data);
    }

    function logout() {
        $_SESSION['ses_login'] = '';
        unset($_SESSION['ses_login']);
        $data['message'] = '';
        /* Hieu add this code to set rememberme */
        if (isset($_COOKIE['ses_login_rm_id'])) {
            $rs_del_rememberme = $this->member->delete_rememberme($_COOKIE['ses_login_rm_id']);
            setcookie('ses_login_rm_id', '', (time() - 3600));
        }
        if ($this->input->post('type') == 'ajax') {
            echo json_encode(array('success' => true));
        } else {
            redirect();
        }
    }

    function file_put_contents($fileName, $data) {
        if (is_array($data)) {
            $data = join('', $data);
        }
        $res = @fopen($fileName, 'w+b');
        if ($res) {
            $write = @fwrite($res, $data);
            if ($write === false) {
                return false;
            } else {
                return $write;
            }
        }
    }

    function chat_line() {
        $ses_login = isset($_SESSION['ses_login']) ? $_SESSION['ses_login'] : '';
        $ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
        $chat_text = isset($_POST['chat_text']) ? $_POST['chat_text'] : '';

        // Kiem tra user truoc khi nhap vao
        $pathblock = getcwd() . '/shout/block_member.txt';
        $arrblock = file($pathblock);
        foreach ($arrblock as $k => $v) {
            $arrpush = explode('|', $v);
            // Lock theo memberid
            if ($arrpush[0] == $ses_login['member_id']) {
                return array();
            }
            // Lock theo IP
            if ($arrpush[1] == $ip) {
                return array();
            }
            // Lock theo username
            if ($arrpush[2] == $ses_login['lb_user_login']) {
                return array();
            }
        }

        // Neu exist session user. 
        // add new massege
        if (!empty($ses_login)) {
            // Thay đổi từ xấu
            $pathword = getcwd() . '/shout/bad_word.php';
            $arrword = file($pathword);
            $chat_text = preg_replace("/(" . $arrword[0] . ")/", '***', $chat_text);



            // them thong tin chat vao file
            $time = time();
            $path = getcwd() . '/shout/messages.txt';
            $arr = file($path);
            // Xoa thong tin chat cu
            if (count($arr) > 1000)
                array_shift($arr);
            $arr[] = $time . '|' . $ses_login['lb_user_login'] . '|' . base64_encode($chat_text) . '|' . $ip . "\n";

            echo $this->file_put_contents($path, implode('', $arr));
        }else {
            return array();
        }

        //$data = $this->build_data_chat_line();
        //$rs = $this->member->add_line($data);
    }

    function build_data_chat_line() {
        $ses_login = isset($_SESSION['ses_login']) ? $_SESSION['ses_login'] : '';
        if (!empty($ses_login)) {
            $dataUpdate["author"] = $ses_login['lb_user_login'];
            $dataUpdate["text"] = $_POST['chat_text'];
            $dataUpdate["ts"] = date('Y-m-d H:i:s');
            return $dataUpdate;
        } else {
            return array();
        }
    }

}

/* End of file Banner.php */
/* Location: site/controllers/Banner.php */